package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.SearchAdapter;
import me.shurufa.adapter.UserCommentAdapter;
import me.shurufa.model.SearchBookListResponse;
import me.shurufa.model.SearchBookResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.widget.CommentHeader;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.OnPageListener;
import me.shurufa.widget.ViewPageTracker;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.RecyclerViewUtils;

/**
 * 新建界面搜索结果列表Fragment
 *
 * @FileName: me.shurufa.fragments.SearchFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-28 11:15
 */
public class SearchFragment extends BaseListFragment {


    public String searchKey;
    private int mSearchType=-1;
    SearchAdapter searchAdapter;

    @Bind(R.id.find_book_number)
    TextView findBookNumber;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_refresh)
    PtrClassicFrameLayout ptrRefresh;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    public static SearchFragment newInstance(int searchType) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.EXTRA_SEARCH_TYPE, searchType);
        fragment.setArguments(args);
        return fragment;
    }

    public String getSearchUrl(){
        String url = null;
        switch (mSearchType){
            case Constants.SEARCH_BY_ISBN:
                url = NetworkConstants.SEARCH_BOOK_BY_ISBN;
                break;
            case Constants.SEARCH_BY_KEYWORD:
                url = NetworkConstants.SEARCH_BOOK_BY_KEYWORD;
                break;
        }
        return url;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments()!=null){
            mSearchType = getArguments().getInt(Constants.EXTRA_SEARCH_TYPE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();

        dataList = new ArrayList();
        searchAdapter = new SearchAdapter(this,dataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(searchAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addOnScrollListener(mOnScrollListener);
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
            if(state == LoadingFooter.State.Loading) {
                LogUtils.kLog().e("the state is Loading, just wait..");
                return;
            }

            if (hasMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
                loadData(mPage);
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(4.2F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        if (mSearchType==Constants.SEARCH_BY_KEYWORD){
            SearchBookListResponse resp = (SearchBookListResponse) response;
            if (isNew) {
                searchAdapter.clear();
            }
            searchAdapter.append(resp.data.books);
        }else if (mSearchType==Constants.SEARCH_BY_ISBN){
            SearchBookResponse resp = (SearchBookResponse)response;
            if (isNew) {
                searchAdapter.clear();
            }
            searchAdapter.append(resp.data);
        }
        searchAdapter.notifyDataSetChanged();

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, SearchBookListResponse.class);
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    public void refresh() {
        super.refresh();
        findBookNumber.setVisibility(View.GONE);
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void refreshShowPtr(){
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    public void onRefresh() {
        mPage = 1;
        loadData(1);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };

    private void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            if (mSearchType == Constants.SEARCH_BY_KEYWORD) {
                new RequestServerTask<SearchBookListResponse>(SearchBookListResponse.class) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("keyword", searchKey);
                        params.put("page", String.valueOf(page));
                        LogUtils.kLog().e("" + page);
                        return HttpUtil.post(getSearchUrl(), params);
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        endRefreshing();
                    }

                    @Override
                    protected void onSuccess(SearchBookListResponse result) {
                        if (result.data == null || result.data.books == null || result.data.books.length == 0) {
                            hasMore = false;
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                            hasMore = true;
                            if (page == 1) {
                                findBookNumber.setVisibility(View.VISIBLE);
                                findBookNumber.setText(String.format(getString(R.string.found_book), result.data.total));
                            }
                            mPage++;
                            bindData(result, page == 1);
                        }
                    }
                }.start();
            } else if (mSearchType == Constants.SEARCH_BY_ISBN) {
                findBookNumber.setVisibility(View.GONE);
                new RequestServerTask<SearchBookResponse>(SearchBookResponse.class) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("isbn", searchKey);
                        return HttpUtil.post(getSearchUrl(), params);
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        endRefreshing();
                    }

                    @Override
                    protected void onSuccess(SearchBookResponse result) {
                        if (result.data.id == 0L) {
                            searchAdapter.clear();
                            Toast.makeText(getActivity(), "未找到相关书籍", Toast.LENGTH_SHORT).show();
                        } else {
                            hasMore = false;
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                            bindData(result, true);
                        }
                    }
                }.start();

            }
        }
    }

    public void enableRefresh(boolean value) {
        ptrRefresh.setEnabled(value);
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh!=null) {
                        ptrRefresh.refreshComplete();
                        if (searchAdapter.getItemCount() == 0) {
                            showEmptyView();
                        }
                    }
                }
            }, 500);
        }
    }
}
